



import 'dart:io';

import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:oral_cloud/utils/string_utils.dart';




class DownloaderMgr{

  final String localPath;

  DownloaderMgr(this.localPath);






  Future<Null> prepare() async {
    if(StringUtils.isEmpty(localPath)){
      throw Exception('localPath can not be empty!');
    }


    final savedDir = Directory(localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }

  }



  Future startDownload(TaskInfo task) async {
    print('startDownload:task=$task');
    String savedDir=localPath+Platform.pathSeparator+task.id;
    print('savedDir=$savedDir');
    final dir = Directory(savedDir);
    bool hasExisted = dir.existsSync();
    print('startDownload:hasExisted=$hasExisted');
    if (!hasExisted) {
      await dir.create();
    }
    String taskId = await FlutterDownloader.enqueue(
        id: task.id,
        url: task.link,
        headers: {"auth": "test_for_sql_encoding"},
        savedDir: savedDir,
        showNotification: false,
        openFileFromNotification: false);
    return taskId;
  }

  void cancelDownload(String taskId) async {
    await FlutterDownloader.cancel(taskId: taskId);
  }

  void removeDownload(String taskId) async {
    await FlutterDownloader.remove(taskId: taskId,shouldDeleteContent: true);
  }

  void pauseDownload(String taskId) async {
    await FlutterDownloader.pause(taskId: taskId);
  }

  void resumeDownload(String taskId) async {
    await FlutterDownloader.resume(taskId: taskId);
  }

  void retryDownload(String taskId) async {
    await FlutterDownloader.retry(taskId: taskId);
  }



}

class TaskInfo{
  String id;//id
  String link;//下载链接
  String filename;
  String savedDir;
  String taskId;
  int progress = 0;
  DownloadTaskStatus status = DownloadTaskStatus.undefined;//下载状态
  TaskInfo({this.link});

  @override
  String toString() {
    return 'TaskInfo{link: $link,id: $id, taskId: $taskId, progress: $progress, status: $status}';
  }
}